/* Copyright (c) 2004-2024 peigen.info. All rights reserved. */

package info.peigen.hotpot.component.data.repository.wood.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import info.peigen.hotpot.component.data.repository.Repository;
import info.peigen.hotpot.component.data.repository.wood.entity.AbstractCreateTimeWithoutPartnerIdEntity;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.data.annotation.Tran;
import org.noear.wood.BaseMapper;
import org.noear.wood.annotation.Db;

import java.util.Date;
import java.util.List;

/**
 * <b>(AbstractWoodWithoutPartnerIdRepository)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/8/16
 */
@Slf4j
@SuppressWarnings("unused")
public class AbstractWoodWithoutPartnerIdRepository<M extends BaseMapper<T>, T extends AbstractCreateTimeWithoutPartnerIdEntity> implements Repository<T> {
    final static String START = "_start";
    final static String END   = "_end";
    public       T      data;
    @Db
    protected    M      mapper;
    /** 默认批次提交数量 */
    int defaultBatchSize = 100;

    public M getMapper() {
        return mapper;
    }

    @Tran
    public void save(T entity) {
        Assert.notNull(entity);
        entity.setCreateTime(new Date());
        insert(entity);
    }

    @Tran
    public void saveOrUpdate(T entity) {
        if (ObjectUtil.isNull(entity)) {
            return;
        }
        entity.setUpdateTime(new Date());
        upsert(entity);
    }

    @Tran
    public void saveOrUpdateBatch(List<T> entities) {
        if (ObjectUtil.isNull(entities)) {
            return;
        }
        entities.stream().filter(entity -> ObjectUtil.isNotNull(entities)).distinct()
                .forEach(this::upsert);
    }

    @Tran
    public void delete(T entity) {
        if (ObjectUtil.isNull(entity) || ObjectUtil.isNull(entity.getId())) {
            return;
        }
        mapper.deleteById(entity.getId());
    }

    @Tran
    public void delete(Integer id) {
        mapper.deleteById(id);
    }

    @Tran
    @SuppressWarnings("UnusedReturnValue")
    private Long insert(T entity) {
        return mapper.insert(entity, true);
    }

    @Tran
    @SuppressWarnings("UnusedReturnValue")
    private Long upsert(T entity) {
        return mapper.upsert(entity, true);
    }
}